package crmdna.api.endpoint;

import javax.annotation.Nullable;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.appengine.api.users.User;

import crmdna.common.APIException;
import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;
import crmdna.common.Utils;
import crmdna.email.EmailProp;
import crmdna.email.GAEEmail;

@Api(name = "email")
public class GAEEmailApi {

	@ApiMethod(path = "sendDummyEmailToLoggedInUser", httpMethod = HttpMethod.POST)
	public APIResponse sendDummyEmailToLoggedInUser(
			@Nullable @Named("client") String client, User user) {
		try {

			if (client == null)
				client = "isha";

			if (null == user)
				throw new APIException(Status.ERROR_LOGIN_REQUIRED,
						"Please log in");

			EmailProp emailProp = new EmailProp();
			emailProp.attachmentName = "test.csv";
			emailProp.bodyHtml = "<h3>Sample html content </h3>";
			emailProp.subject = "Test subject";
			emailProp.toEmailAddresses.add(user.getEmail());
			emailProp.sendCSVAttachment = true;
			emailProp.csvAttachmentData = "first name, last name\nfirst name, last name\nfirst name, last name\n";

			GAEEmail.send(emailProp);

			return new APIResponse(Status.SUCCESS, "Sent dummy email to "
					+ user.getEmail());

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}

	@ApiMethod(path = "sendTestAlertToDevTeam", httpMethod = HttpMethod.POST)
	public APIResponse sendTestAlertToDevTeam(User user, HttpServletRequest req) {
		try {

			if (null == user)
				throw new APIException(Status.ERROR_LOGIN_REQUIRED,
						"Please log in as supper user");

			if (!user.getEmail().equals(crmdna.user.User.SUPER_USER))
				throw new APIException(Status.ERROR_INSUFFICIENT_PERMISSION,
						"This call is only allowed for super user");

			Utils.sendAlertEmailToDevTeam("TestClient", new RuntimeException(
					"Test exception: please ignore"), req, user.getEmail());			

			return new APIResponse(Status.SUCCESS, "Success");

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
}
